package unimelb.filesync.common.network;

import java.security.Key;

import unimelb.filesync.common.crypto.CryptoUtils;

public class RsaEncryptedNetworkConnection extends NetworkConnection {

    private final NetworkConnection connection;

    private final Key key;

    private final CryptoUtils cryptoUtils;

    public RsaEncryptedNetworkConnection(NetworkConnection connection, Key key) {
        super();
        this.connection = connection;
        this.key = key;
        this.cryptoUtils = new CryptoUtils();
    }

    @Override
    public void writeString(String msg) {
        final byte[] encryptedData = cryptoUtils.encryptRsa(msg.getBytes(), key);
        final String encodedData = cryptoUtils.encode(encryptedData);
        connection.writeString(encodedData);
    }

    @Override
    public String readString() {
        final String encodedString = connection.readString();
        if (encodedString == null) {
            return null;
        }

        final byte[] decodedData = cryptoUtils.decode(encodedString);
        final byte[] decryptedData = cryptoUtils.decryptRsa(decodedData, key);
        return new String(decryptedData);
    }
}
